import { ref } from 'vue'

import { useUserAPI } from '@/server'


const unSendText: string = "发送验证码"
const cooingText: string = "{count}秒后重试"

export function useUserEmailSender() {

    const { sendVcode } = useUserAPI();

    // 验证码按钮显示信息
    const msg = ref<string>(unSendText)


    // 验证码按钮是否进入了倒数读秒提示
    const isCooing = ref<boolean>(false)

    // 触发验证码消息倒数
    const interCall = function (): void {
        isCooing.value = true;

        let count = 60

        const innter = setInterval(() => {
            count--;
            msg.value = cooingText.replace("{count}", String(count));
            if (count == 0) {
                isCooing.value = false;
                msg.value = unSendText;
                clearInterval(innter);
            }

        }, 1000)
    }

    // 发送验证码
    const send = (email: string) => {
        if(!email||email.trim() === ""){
            alert("邮箱地址不能为空");
            return;
        }

        sendVcode(email).then(res => {
            const { data } = res;
            if (data.code == 200) {
                interCall();
            } else {
                alert(data.msg);
            }
        })
    }

    return {
        msg,
        isCooing,
        send
    }

}